//
//  ZFRegionView.swift
//  map
//
//  Created by fyzq on 2024/2/5.
//

import Foundation
import RxSwift
import CollectionKit
import MapboxMaps

class ZFRegionView :ZFBaseView {
    
    var stackView:UIStackView!
    var subject = PublishSubject<FeatureCollection>()
    var grabberView:UIView!
//    private var selectedIndex = -1;

    private var shengReginView:ZFRegionSelectedView!
    private var shiReginView:ZFRegionSelectedView!
    private var quReginView:ZFRegionSelectedView!
    override init(frame: CGRect) {
        super.init(frame: frame)
        setZFRegionView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setZFRegionView(){
        
        backgroundColor = R.color.bg()
        
        shengReginView =  ZFRegionSelectedView()
        shengReginView.code = "100000_full"
        shengReginView.titleLabel.text = "省"
        
        shiReginView =  ZFRegionSelectedView()
        shiReginView.titleLabel.text = "市"
        
        quReginView =  ZFRegionSelectedView()
        quReginView.titleLabel.text = "区"
        
        stackView =  UIStackView(arrangedSubviews: [shengReginView,shiReginView,quReginView])
        stackView.axis = .horizontal
        stackView.spacing = 10
        stackView.alignment = .center
        stackView.distribution = .fillEqually
        
        addSubview(stackView)
        
        stackView.snp.makeConstraints { make in
            make.top.equalTo(UIDevice.safeAreaInsets.top + 20)
            make.left.equalTo(15)
            make.right.equalTo(-15)
        }
        
        grabberView = UIView()
        grabberView.addRadius(radius: 2)
        grabberView.backgroundColor = UIColor(displayP3Red: 0.76, green: 0.77, blue: 0.76, alpha: 1.0)
        addSubview(grabberView)
        grabberView.snp.makeConstraints { make in
            make.top.equalTo(stackView.snp.bottom).offset(20)
            make.width.equalTo(40)
            make.height.equalTo(4)
            make.bottom.equalTo(-10)
            make.centerX.equalToSuperview()
        }
        shengReginView.subject.subscribe(onNext: {[weak self] feature in
            guard let self = self,let sCode = self.shengReginView.code else {return}
            let code = String(Int(feature.properties!.rawValue["adcode"] as! Double))
            if code == sCode {
                return
            }
            let codeName = feature.properties!.rawValue["name"] as! String
            self.shengReginView.codeName = codeName;
            self.shengReginView.isOpen = false
            self.shiReginView.code = code + "_full"
            self.shiReginView.codeName = "请选择"
            self.quReginView.code = nil
            self.quReginView.codeName = "请选择"
            self.subject.onNext(FeatureCollection(features: [feature]))
        
        }).disposed(by: dis)
        
        shiReginView.subject.subscribe(onNext: {[weak self] feature in
            guard let self = self,let sCode = self.shiReginView.code else {return}
            let code = String(Int(feature.properties!.rawValue["adcode"] as! Double))
            if code == sCode {
                return
            }
            let codeName = feature.properties!.rawValue["name"] as! String
            self.shiReginView.codeName = codeName;
            self.shiReginView.isOpen = false
            self.quReginView.code = code  + "_full"
            self.quReginView.codeName = "请选择"
            self.subject.onNext(FeatureCollection(features: [feature]))
        
        }).disposed(by: dis)
        
        quReginView.subject.subscribe(onNext: {[weak self] feature in
            guard let self = self,let sCode = self.quReginView.code else {return}
            let code = String(Int(feature.properties!.rawValue["adcode"] as! Double))
            if code == sCode {
                return
            }
            let codeName = feature.properties!.rawValue["name"] as! String
            self.quReginView.codeName = codeName;
            self.quReginView.isOpen = false
            self.subject.onNext(FeatureCollection(features: [feature]))
        
        }).disposed(by: dis)
    
    }
    
    deinit {
        print("销毁")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        
        jk.addCorner(conrners: [UIRectCorner.bottomLeft,UIRectCorner.bottomRight], radius: 10)
    }
}




class ZFRegionListView :ZFBaseView {

    private let collectionView = CollectionView()
    let dataSource = ArrayDataSource<Feature>(data: [])
    var subject = PublishSubject<Feature>()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setZFRegionListView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setZFRegionListView(){
           
        let provider = BasicProvider(
            dataSource: dataSource,
            viewSource: {(view: UILabel, data:Feature, index: Int) in
                view.text = (data.properties!.rawValue["name"] as! String);
                view.textAlignment = .center
                view.font = UIFont.systemFont(ofSize: 14)
                view.backgroundColor = R.color.color_f1()
                view.textColor = R.color.color_3c()
                view.addRadius(radius: 5)
            },
            sizeSource: {(_,_,size )-> CGSize in
                return CGSize(width: size.width, height: 28.0)
            },
            layout: FlowLayout(spacing: 5,alignItems: .start).inset(by: UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5))) {[weak self] context in
                guard let self = self else {return}
                self.subject.onNext(context.data)
            }
            collectionView.provider = provider;
            collectionView.showsVerticalScrollIndicator = false
            addSubview(collectionView)
            collectionView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
    }
}



class ZFRegionSelectedView : ZFBaseView {
    
    private var arrowLabel :UILabel!
    private var listView:ZFRegionListView!
    private var contentLabel :UILabel!
    @objc dynamic var isOpen:Bool = false
    var titleLabel :UILabel!
    var code :String?
    var codeName:String = "请选择"{
        didSet{
            contentLabel.text = codeName
        }
    }
    var subject = PublishSubject<Feature>()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setZFRegionSelectedView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setZFRegionSelectedView(){
        self.isUserInteractionEnabled = true
        titleLabel = UILabel()
        titleLabel.text = "省"
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.systemFont(ofSize: 12)
        titleLabel.textColor = R.color.color_33()
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(5)
            make.left.equalTo(5)
            make.bottom.equalTo(-5)
            make.width.height.equalTo(22)
        }
        
        contentLabel = UILabel()
        contentLabel.text = "请选择"
        contentLabel.font = UIFont.systemFont(ofSize: 12)
        contentLabel.textColor = R.color.color_33()
        addSubview(contentLabel)
        contentLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel.snp.right).offset(5)
            make.centerY.equalToSuperview()
        }
        
        
        arrowLabel = UILabel()
        arrowLabel.text = .icon(icon: .ic_arrow_right)
        arrowLabel.textAlignment = .center
        arrowLabel.font = UIFont.iconfont(size: 22)
        arrowLabel.textColor = R.color.color_33()
        addSubview(arrowLabel)
        arrowLabel.snp.makeConstraints { make in
            make.left.equalTo(contentLabel.snp.right).offset(5)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(22)
            make.right.equalTo(-5)
        }
        arrowLabel.transform = CGAffineTransform(rotationAngle: Double.pi / 2)
        
        jk.addGestureTap{[weak self] _ in
            guard let self = self,let code = code else {return}
            self.isOpen = !self.isOpen
        }
        
        self.rx.observeWeakly(Bool.self, "isOpen").skip(1).subscribe(onNext: {[weak self]bo in
            guard let self = self,let code = code else {return}
            if bo! {
                self.show()
                self.regionAction(code: code).subscribe(onNext:{[weak self]data in
                    guard let self = self else {return}
                    self.listView.dataSource.data = data.features
                }).disposed(by: self.dis)
            }else {
                self.hidden()
            }
        }).disposed(by: dis)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        jk.addCorner(conrners: UIRectCorner.allCorners, radius: 4, borderWidth: 1, borderColor: R.color.color_66()!)
    }

    
  
}
extension ZFRegionSelectedView {
    
    fileprivate func regionAction(code:String) ->Observable<FeatureCollection>{
        return Observable.create { observer in
         return  ZFNetRequest.geojson(code: code).subscribe(onNext: {[weak self]data in
             guard let self = self else {return}
             do {
                 let  featureCollection = try JSONDecoder().decode(FeatureCollection.self, from: data) 
                 observer.onNext(featureCollection)
                 observer.onCompleted()
             } catch {
                 print("Error parsing data: \(error)")
             }
         })
        }
    }
    
}
extension ZFRegionSelectedView {
    fileprivate func show(){
        guard let vc = self.jk.currentVC,
            let view = vc.view else {
            return
        };
        listView = ZFRegionListView()
        listView.backgroundColor = .white
        view.addSubview(listView)
        listView.snp.makeConstraints { make in
            make.top.equalTo(self.snp.bottom)
            make.left.right.equalTo(self)
            make.height.equalTo(1)
        }
        view.layoutIfNeeded()
        UIView.animate(withDuration: 0.3) {
            self.listView.snp.updateConstraints { make in
                make.height.equalTo(140)
            }
            self.arrowLabel.transform = CGAffineTransform(rotationAngle: Double.pi*1.5)
            view.layoutIfNeeded()
        }
        listView.subject.subscribe(onNext: {[weak self]feature in
            guard let self = self else {return}
            self.subject.onNext(feature)
        }).disposed(by: listView.dis)
        

        listView.jk.addShadow(shadowColor:  R.color.color_3c()!, shadowOffset: CGSize(width: 0, height: 1), shadowOpacity: 0.3, shadowRadius: 5)
        listView.jk.addCorner(conrners: UIRectCorner.allCorners, radius: 5)
    }
    fileprivate func hidden(){
        guard let vc = self.jk.currentVC,
            let view = vc.view else {
            return
        };
        UIView.animate(withDuration: 0.3) {
            self.listView.snp.updateConstraints { make in
                make.height.equalTo(0)
            }
            self.arrowLabel.transform = CGAffineTransform.init(rotationAngle: Double.pi/2)
            view.layoutIfNeeded()
        } completion: { bo in
            self.listView.removeFromSuperview()
        }
    }
}
